#import "PhoneRegisterViewController.h"
#import "AuthCodeViewController.h"
#import "PhoneNumberChecker.h"
#import "PopUIManager.h"
#import "JsonUtil.h"
#import "NetWorkManager.h"
#import "ModifyPhoneViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface PhoneRegisterViewController ()

@end

@implementation PhoneRegisterViewController
@synthesize numberInput,receiveCode;

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden=NO;
    if (_isRegister) {
        self.navigationItem.title=@"注册";
    }else {
        self.navigationItem.title=@"修改手机号";
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    [self customView];

    numberInput.delegate = self;
    touchEnable = false;
    
    if (!_isRegister) {
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        _tipLabel.text = @"您将收到验证身份的短信来更换新手机号";
    }
}

- (UIStatusBarStyle) preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

-(void)customView
{
    numberInput.layer.cornerRadius=4.0f;
    numberInput.layer.masksToBounds=YES;
    numberInput.layer.borderColor=[[UIColor redColor]CGColor];
    numberInput.layer.borderWidth= 1.0f;
    
    UILabel *leftView = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 60, 40)];
    leftView.text =@"+86";
    leftView.textColor = [UIColor whiteColor];
    leftView.textAlignment = NSTextAlignmentCenter;
    leftView.backgroundColor = UIColorMake(255, 111, 111);
    numberInput.leftView = leftView;
    numberInput.leftViewMode = UITextFieldViewModeAlways;
    
    receiveCode.layer.cornerRadius = 4.0f;
    receiveCode.backgroundColor =UIColorMake(171,171,171);
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
}

- (IBAction)receiveCodeCallback{
    
    if (touchEnable == true) {
        [self.view endEditing:YES];
        NSString *account = numberInput.text;
        NSUInteger type =1;
        if(_isRegister){
            type = 1;
        }else{
            type = 3;
        }
        NSString *dataString = [JsonUtil convertDictionaryToJson:[[NSDictionary alloc]initWithObjectsAndKeys:@(type), @"type", account, @"account", @(1), @"codetype", nil]];
        
        PopUIManager *popUIMgr = [PopUIManager getInstanse];
        [popUIMgr showWaitingUI:self.view];
        
        [[NetWorkManager getInstanse] requestURLAsynMessage:USER_GET_AUTH_CODE data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (connectionError) { //连接失败
                NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
                NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
                [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
            }else{//连接成功，判断是否有数据返回
                if (data) {
                    NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                    NSLog(@"数据字典: %@", dict);
                    
                    if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                        //登录失败，弹窗提示
                        NSString *ret_msg;
                        switch ([[dict objectForKey:@"retCode"] integerValue]) {
                            case 10007:{
                                ret_msg= @"该手机号已经注册过";
                                break;
                            }case 1:{
                                ret_msg= @"手机号格式错误";
                                break;
                            }case 3:{
                                ret_msg= @"Success";
                                break;
                            }case 4:{
                                ret_msg= @"数据库操作异常，请稍后再试";
                                break;
                            }default:{
                                ret_msg= @"未知错误";
                                break;
                            }
                        }
                        if (![ret_msg isEqual:@"Success"]) {
                            [popUIMgr popAlertView:nil title:@"提示" message:ret_msg cancelButtonTitle:@"确定"];
                            [popUIMgr removeWaitingUI];
                            return;
                        }else{
                            if(_isRegister){
                            AuthCodeViewController *authCodeViewController = [[AuthCodeViewController alloc]init];
                                authCodeViewController.phoneNum = account;
                            [self.navigationController pushViewController:authCodeViewController animated:YES];
                            }else{
                                ModifyPhoneViewController *modifyPhone = [[ModifyPhoneViewController alloc]init];
                                modifyPhone.phone =account;
                                [self.navigationController pushViewController:modifyPhone animated:YES];
                            }
                            
                        }
                    }else{
                        [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
                }
            }
            [popUIMgr removeWaitingUI];
        }];
    }else{
        debugLog(@"电话号码位数不满足~");
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (range.location > 10) {
        return NO;
    }else{
        if (numberInput.text.length == 10) {
            NSString *s = [numberInput.text stringByAppendingString:string];
            if ([PhoneNumberChecker isValidNumber:s]) { //检查号码是否合法
                receiveCode.backgroundColor = UIColorMake(90, 165, 248);
                touchEnable = true;
            }
        }else{
            receiveCode.backgroundColor = UIColorMake(171, 171, 171);
            touchEnable = false;
        }
        return YES;
    }
}

@end
